package com.lagou.filter;

import com.lagou.client.UserClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private UserClient userClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String serviceName = request.getPath().pathWithinApplication().subPath(1, 2).value();
        //用户微服务和验证码微服务的请求不不过滤
        if (serviceName.equals("code") || serviceName.equals("user")) {
            return chain.filter(exchange);
        }

        List<HttpCookie> httpCookieList = request.getCookies().get("token");
        if (CollectionUtils.isEmpty(httpCookieList)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//状态码，未经授权
            String data = "token not found";
            DataBuffer dataBuffer = response.bufferFactory().wrap(data.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }
        String lagouToken = httpCookieList.get(0).getValue();
        //String lagouToken = exchange.getAttribute("lagouToken");
        String email = userClient.info(lagouToken);
        //token不合法
        if (StringUtils.isBlank(email)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//状态码，未经授权
            String data = "Request be denied!";
            DataBuffer dataBuffer = response.bufferFactory().wrap(data.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }
        //放行
        return chain.filter(exchange);
    }


    //过滤器的执行顺序
    @Override
    public int getOrder() {
        return 0;
    }
}
